package com.afei.filepicker;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class FileAdapter extends MyRecyclerAdapter<File> implements MyRecyclerAdapter.OnItemClickListener,
        MyRecyclerAdapter.OnItemLongClickListener {

    private static final String TAG = "FileAdapter";
    private File mRootDir;
    private File mCurrentDir;
    private boolean[] mCheckedFlags;
    private boolean mChooseMode;
    private OnDirChangeListener mOnDirChangeListener;

    /* 文件名排序规则：文件夹在前，文件在后，按字母顺序*/
    private Comparator<File> mFileComparator = new Comparator<File>() {
        @Override
        public int compare(File file1, File file2) {
            if (file1.isDirectory() && file2.isFile()) {
                return -1;
            }
            if (file1.isFile() && file2.isDirectory()) {
                return 1;
            }
            return file1.getName().toLowerCase().compareTo(file2.getName().toLowerCase());
        }
    };

    /* 文件名过滤规则：不显示点号开头的文件*/
    private FilenameFilter mFilenameFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            if (name.startsWith(".")) { //点号开头的文件一般都不需要
                return false;
            }
            return true;
        }
    };

    public FileAdapter(Context context, String rootPath) {
        mContext = context;
        mList = new ArrayList<>();
        mLayoutId = R.layout.item_file_list;
        setOnItemClickListener(this);
        setOnItemLongClickListener(this);

        mRootDir = new File(rootPath);
        mCurrentDir = mRootDir;
        updateList();
    }

    @Override
    public void convert(ViewHolder holder, File file, final int position) {
        ImageView fileIcon = holder.getView(R.id.item_file_icon);
        TextView filename = holder.getView(R.id.item_file_name);
        CheckBox checkBox = holder.getView(R.id.item_check_box);
        ImageView arrowIcon = holder.getView(R.id.item_arrow);

        int resId = file.isDirectory() ? R.mipmap.folder_style_yellow : R.mipmap.file_style_yellow;
        fileIcon.setImageResource(resId);
        filename.setText(file.getName());
        checkBox.setVisibility(mChooseMode ? View.VISIBLE : View.GONE);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mCheckedFlags[position] = isChecked;
            }
        });
        checkBox.setChecked(mCheckedFlags[position]);
        if (file.isDirectory() && !mChooseMode) {
            arrowIcon.setVisibility(View.VISIBLE);
        } else {
            arrowIcon.setVisibility(View.GONE);
        }
    }

    public boolean isChooseMode() {
        return mChooseMode;
    }

    public boolean isRootDir () {
        if (mRootDir == null || mCurrentDir == null) {
            return true;
        }
        return mRootDir.getAbsolutePath().equals(mCurrentDir.getAbsolutePath());
    }

    public void quitMode() {
        mChooseMode = false;
        Arrays.fill(mCheckedFlags, false);
        notifyDataSetChanged();
    }

    public void backParent() {
        if (isRootDir()) {
            Log.w(TAG, "can't back to parent dir, is root dir!");
            return;
        }
        mCurrentDir = mCurrentDir.getParentFile();
        updateList();
        if (mOnDirChangeListener != null) {
            mOnDirChangeListener.onDirChangeListener(mCurrentDir);
        }
    }

    public ArrayList<String> getChoosePaths() {
        if (!mChooseMode) {
            return null;
        }
        ArrayList<String> result = new ArrayList<>();
        for (int i = 0; i < mCheckedFlags.length; i++) {
            if (mCheckedFlags[i]) {
                result.add(mList.get(i).getAbsolutePath());
                Log.d(TAG, "add path: " + mList.get(i).getAbsolutePath());
            }
        }
        return result.size() > 0 ? result : null;
    }

    public void setOnDirChangeListener(OnDirChangeListener onDirChangeListener) {
        mOnDirChangeListener = onDirChangeListener;
    }

    @Override
    public void onItemClick(View view, int position) {
        if (mChooseMode) {
            mCheckedFlags[position] = !mCheckedFlags[position];
            CheckBox checkBox = view.findViewById(R.id.item_check_box);
            checkBox.setChecked(mCheckedFlags[position]);
        } else {
            File file = mList.get(position);
            if (file.isDirectory()) {
                mCurrentDir = new File(file.getAbsolutePath());
                updateList();
                if (mOnDirChangeListener != null) {
                    mOnDirChangeListener.onDirChangeListener(mCurrentDir);
                }
            }
        }
    }

    public void updateList() {
        File[] files = mCurrentDir.listFiles(mFilenameFilter);
        mList.clear();
        if (files != null && files.length > 0) {
            Arrays.sort(files, mFileComparator);
            mList.addAll(Arrays.asList(files));
            mCheckedFlags = new boolean[mList.size()];
        }
        notifyDataSetChanged();
    }

    @Override
    public void onItemLongClick(View view, int position) {
        if (!mChooseMode) {
            mChooseMode = true;
            mCheckedFlags[position] = true;
            notifyDataSetChanged();
        }
    }

    interface OnDirChangeListener {

        void onDirChangeListener(File currentDirectory);
    }

}
